void getcursorxy(int* x, int* y) {
  bwprintf( COM2, "\x1b[6n" );
  int cx = 0, cy = 0;
  unsigned char c;
  c = bwgetc( COM2 ); // eat ESC
  c = bwgetc( COM2 ); // eat [
  while ( ( c = bwgetc( COM2 ) ) ) {
    if (c >= '0' && c <= '9') cx = cx*10+(c-'0');
    else break;
  }
  while ( ( c = bwgetc( COM2 ) ) ) {
    if (c >= '0' && c <= '9') cy = cy*10+(c-'0');
    else break;
  }
  *x = cx; *y = cy;
}

void setcursorxy(int x, int y) {
  bwprintf( COM2, "\x1b[%d;%dH", y, x );
}

void movecursorxy(int dx, int dy) { 
  if (dx < 0) {
    bwprintf( COM2, "\x1b[%dD", -dx ); 
  } else if (dx > 0) {
    bwprintf( COM2, "\x1b[%dC", dx );
  }
  if (dy < 0) {
    bwprintf( COM2, "\x1b[%dA", -dy );
  } else if (dy > 0) {
    bwprintf( COM2, "\x1b[%dB", dy );
  }
}   

void setscrcolor(int fg, int bg) {
  bwprintf( COM2, "\x1b[%d;%dm", fg, bg );
}

void clearline() {
  bwprintf( COM2, "\x1b[2K" );
}

void cleardown() {
  bwprintf( COM2, "\x1b[J" );
}

void clearscr() {
  bwprintf( COM2, "\x1b[2J" );
}

void savecursor() {
  bwputc( COM2, '\x1b' );
  bwputc( COM2, '7' );
}

void unsavecursor() {
  bwputc( COM2, '\x1b' );
  bwputc( COM2, '8' );
}
